from datetime import datetime

from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from .authentications import generate_jwt
from .serializers import *
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated


# Create your views here.

class LoginView(APIView):
    def post(self, request):
        # 1.验证数据是否可用
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            user.last_login = datetime.now()
            user.save()
            token = generate_jwt(user)
            return Response({'token': token, 'user': UserSerializer(user).data}, status=status.HTTP_200_OK)
        else:
            print(serializer.errors)
            detail = list(serializer.errors.values())
            return Response({"detail": f"参数验证失败:原因是{'+'.join(de[0] for de in detail)}"},
                            status=status.HTTP_400_BAD_REQUEST)


class ResetPwdView(APIView):

    def post(self, request):
        serializer = ResetPwdSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            pwd1 = serializer.validated_data.get('pwd1')
            request.user.set_password(pwd1)
            request.user.save()
            return Response({"detail": "修改成功"}, status=status.HTTP_200_OK)
        else:
            print(serializer.errors)
            detail = list(serializer.errors.values())
            return Response({"detail": f"参数验证失败:原因是{'+'.join(de[0] for de in detail)}"},
                            status=status.HTTP_400_BAD_REQUEST)

